<template>
  <div id="Header">
    <!-- 内容主体 -->
    <div class="content_reg">
      <div class="header">
        <h1>忘记密码</h1>
      </div>
      <el-form
        label-width="120px"
        size="large"
        ref="reg_data_ref"
        :model="reg_data"
        :rules="reg_data_rules"
      >
        <div class="block-container">

          <div class="form-container">
            <el-form-item
              label="手机号码"
              prop="phone"
              v-if="false"
            >
              <el-input
                @change="changePhone"
                v-model="reg_data.phone"
                placeholder="请输入手机号码"
              />
              <el-button
                plain
                class="ipn_btn"
                @click="handleCoundDown(reg_data.phone)"
                :disabled="disabled"
              >{{ btnText }}
              </el-button>
            </el-form-item>
            <el-form-item
              label="手机号码"
              prop="phone"
            >
              <PhoneSendCode v-model="reg_data.phone" />
            </el-form-item>

            <el-form-item
              label="验证码"
              prop="code"
              v-if="false"
            >
              <el-input
                @change="changePhone"
                placeholder="请输入验证码"
                v-model="reg_data.code"
              >
                <template #append>
                  <el-image
                    @click="update_validate_image"
                    class="code-image"
                    :src="validate_image_url"
                  >
                    <template #error>
                      <el-text
                        type="info"
                        size="small"
                      >点击刷新</el-text>
                    </template>
                  </el-image>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item
              label="手机验证码"
              prop="phoneCode"
            >
              <el-input
                v-model="reg_data.phoneCode"
                placeholder="请输入手机验证码"
              />
            </el-form-item>
            <el-form-item
              label="输入密码"
              prop="password"
            >
              <el-input
                v-model="reg_data.password"
                show-password
                type="password"
                placeholder="请输入密码"
              />
            </el-form-item>
            <el-form-item
              label="再次输入密码"
              prop="passwordToo"
            >
              <el-input
                v-model="reg_data.passwordToo"
                show-password
                type="password"
                placeholder="请再次输入密码"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                :loading="reg_loading"
                @click="handleJumpLoginPage"
                class="open_serve"
              >提交</el-button>
            </el-form-item>
          </div>
        </div>

      </el-form>
    </div>
    <!-- 验证码弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogText"
      width="20%"
      :before-close="handleClose"
    >
      <span>欢迎参与AI Will综合素养挑战赛，
        您的动态验证为【<b>{{ codePhone }}</b>】，
        非本人操作请忽略，感谢您为科创事业添砖加瓦！
      </span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogVisible = false"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script  setup>
import { useRouter, useRoute } from "vue-router";
import { ref, onMounted } from "vue"
import { useUserStore } from "@/store/user";
import { ElMessage } from "element-plus"
import { useValidateImage } from "@/hooks/useValidateImage"
import { sendCode, forgetPassword } from '@/api/index'
const { validate_image_url, update_validate_image } = useValidateImage();
import PhoneSendCode from "@/components/phone-send-code/index.vue"


const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const checkPhone = (rule, value, callback) => {
  const phoneReg = /^1[3|4|5|6|7|8|9][0-9]{9}$/
  if (!value) {
    callback(new Error('手机号码不能为空'))
  }
  if (phoneReg.test(value)) {
    callback()
  } else {
    callback(new Error('手机号码格式错误'))
  }
}

const checkPass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'));
  } else {
    callback();
  }
};
const checkPass2 = (rule, value, callback) => {

  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== reg_data.value.password) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
};

const reg_data_ref = ref();
const reg_data_rules = ref({
  phone: [
    {
      required: true,
      validator: checkPhone,
    }
  ],
  password: [
    {
      type: 'string',
      required: true,
      validator: checkPass,
      trigger: 'blur',
    }
  ],
  passwordToo: [
    {
      type: 'string',
      required: true,
      validator: checkPass2,
      trigger: 'blur',
    }
  ],
  //   code: [
  //     {
  //       type: 'string',
  //       required: true,
  //       message: '请输入验证码',
  //       trigger: 'blur',
  //     }
  //   ],
  phoneCode: [
    {
      type: 'string',
      required: true,
      message: '请输入手机验证码',
      trigger: 'blur',
    }
  ],

});
/**
 * 跳转到登录页
 */
const handleJumpLoginPage = async () => {
  reg_data_ref.value.validate(async (v) => {
    if (!v) {
      return;
    }
    let res = await forgetPassword(reg_data.value)
   
    if (res.success) {
      ElMessage.success(res.message)
      router.push("/auth/login");
    } else {
      ElMessage.error(res.message)
      update_validate_image();
    }

  });
};


// 获取验证码
const dialogVisible = ref(false)
const dialogText = ref('手机验证码(测试阶段-流程使用) ')
const codePhone = ref('')
const handleSendCode = async (phone) => {
  let res = await sendCode({ phone })

  if (res.success) {
    dialogVisible.value = true
    codePhone.value = res.entity
    ElMessage.success(res.message)
  } else {
    ElMessage.error(res.message)
  }
}


// 60秒验证码
const btnText = ref('获取验证码')
const countdown = ref(60)
const disabled = ref(true)
const handleCoundDown = (phone) => {
  if (reg_data.value.code == '') {
    ElMessage.error('请填写验证码')
    return;
  }
  if (disabled.value) {
    return; // 如果按钮已禁用，则不执行任何操作
  }

  handleSendCode(phone)
  let timer = setInterval(() => {
    if (countdown.value <= 0) {
      disabled.value = false
      btnText.value = '获取验证码'
      clearInterval(timer)
      countdown.value = 60
    } else {
      btnText.value = countdown.value + 's 后重试'
      countdown.value--
      disabled.value = true
    }
  }, 1000)
}

/**
 * 登录数据
 */
const reg_data = ref({
  "phone": "",   //手机号
  "password": "",   //密码
  "passwordToo": '',  // 再次输入密码
  "code": "",  // 验证码
  "phoneCode": "", // 手机验证码

});


// 必须判断成功后才可以点击获取验证码
const changePhone = () => {
  reg_data_ref.value.validate(async (valid, roles) => {
   
    if (!roles.phone) {
      disabled.value = false;
    } else {
      disabled.value = true;
    }
  });
}
/**
 * onMounted
 */
onMounted(() => {
  reg_data.value.channel = route.query.channel ?? "";
})
</script>

<style lang="scss" scoped>
#Header {
  height: 100vh;
  width: 100%;
  overflow-y: auto;
  //   background: #8473f724;
  background-image: url('@/assets/images/login_bgc.png');
  padding-top: 180px;
  padding-bottom: 32px;
  box-sizing: border-box;

  .content_reg {
    display: flex;
    flex-direction: column;
    width: 740px;
    border-radius: 16px;
    background: #fff;
    margin: 0 auto;
    box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.05);
    padding: 20px;

    .block-container {
      margin-top: 32px;

      .form-container {
        width: 512px;
        padding-top: 16px;
      }
    }
  }
}

:deep(.el-input-group__append) {
  padding: 0;
  cursor: pointer;
  box-sizing: border-box;
}

.code-image {
  height: 40px !important;
  cursor: pointer;
  text-align: center;
}

.inp_ip {
  width: 270px;
}

.ipn_btn {
  position: absolute;
  right: 0;
}

// 忘记密码提交按钮
.open_serve {
  width: 120px;
}
</style>